package com.ruoyi.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * 地址转经纬度（使用高德地图获取地址信息的经纬度）
 * @author qzz
 */
@Component
public class AddressLocationUtil {
    /**
     * Key
     */
    //private static String KEY="d73cc951a96637a251a9a2446b48ce9c";
    private static String KEY="a0b318de35332e2f14313955b699f8d0";

    //private static String KEY="39fcf04d6c9deb64c8436b40445c829e";

    public  static String GD_URL="https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";

    /**
     * 成功标识
     */
    private static String SUCCESS_FLAG="1";

    /**
     * 根据地址获取对应的经纬度信息
     * @param address
     * @return
     */
    public  String getLonAndLatByAddress(String address){
        String location="";
           String GD_URL1="https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";
        GD_URL1 = String.format(GD_URL1, address, KEY);
        //高德接口返回的是JSON格式的字符串
        String queryResult = getResponse(GD_URL1);
        JSONObject obj = JSONObject.parseObject(queryResult);
        if(String.valueOf(obj.get("status")).equals(SUCCESS_FLAG)){
            JSONArray geocodes = obj.getJSONArray("geocodes");
            if(ObjectUtils.isEmpty(geocodes)){
                throw new RuntimeException("地址转换经纬度失败,解析失败" );
            }
            JSONObject jsonObject = geocodes.getJSONObject(0);
            location = jsonObject.getString("location");
           /* JSONObject jobJSON = JSONObject.parseObject(obj.get("geocodes").toString().substring(1, obj.get("geocodes").toString().length() - 1));
            location = String.valueOf(jobJSON.get("location"));*/
        }else{
            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
        }
        return location;
    }
    /**
     * 发送请求
     *
     * @param serverUrl 请求地址
     */
    private  String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static void main(String[] args) {
        AddressLocationUtil util=new AddressLocationUtil();
        //String address="湖北省武汉市汉阳区江城大道366号绿地中央广场3-16号商铺";
        String address="成都高新区管委会";
        String location=util.getLonAndLatByAddress(address);
        System.out.println("经纬度：" + location);


    }
}

